package cn.yonyong.base.project.others.webScrap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Describtion Todo
 * @Author yonyong
 * @Date 2019/10/15 9:28
 * @Version 1.0.0
 **/
public class ExpressUtils {
    private final static String EXPRESS_URL = "https://sp0.baidu.com/9_Q4sjW91Qh3otqbppnN2DJv/pae/channel/data/asyncqury";
    private final static String APP_ID = "4001";
    private static String COOKIES_TOKEN = "globacsrftoken=saiXdCuK-0pKL63zxa0IAW9hwLht3CGPzw8XzkYkSFQ;";
    private static String COOKIES_BAIDUID = "BAIDUID=58E58018908655AB9BD547073B7AE983:FG=1;";
    private static String COOKIES_BIDUPSID = "BIDUPSID=58E58018908655AB9BD547073B7AE983;";
    private static String COOKIES_PSTM = "PSTM=1571043643";
    public static void main(String[] args) {
        String jsonString = getInfo("773005348100562","申通快递");
        System.out.println(jsonString);
    }

    /**
     *  查询快递接口
     */
    public static String getInfo(String numberCode, String type){
        RestTemplate restTemplate = new RestTemplate();
        //封装cookies
        HttpHeaders requestHeaders = new HttpHeaders();
        List<String> tempList = new ArrayList<>();
        tempList.add(COOKIES_TOKEN);
        tempList.add(COOKIES_BAIDUID);
        tempList.add(COOKIES_BIDUPSID);
        tempList.add(COOKIES_PSTM);
        requestHeaders.put("Cookie",tempList);
        HttpEntity<String> requestEntity = new HttpEntity<>(null,requestHeaders);
        String expressCompanyNumber = getCompanyInfo(type);
        String url = EXPRESS_URL +
                    "?appid="+APP_ID +
                    "&com="+expressCompanyNumber +
                    "&nu="+numberCode;
        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET,requestEntity,String.class);
        JSONObject jsonObject = JSONObject.parseObject(result.getBody());
        //去除无用信息
        if (null != jsonObject.getJSONObject("data").get("kuaidiSource")){
            jsonObject.getJSONObject("data").remove("kuaidiSource");
        }
        if (null != jsonObject.getJSONObject("data").get("source")){
            jsonObject.getJSONObject("data").remove("source");
        }
        if (null != jsonObject.getJSONObject("data").get("pcAsynInfo")){
            jsonObject.getJSONObject("data").remove("pcAsynInfo");
        }
        return jsonObject.toJSONString();
    }

    /**
     * 读取json文件
     */
    private static String readJsonData(){
        URL url= ExpressUtils.class.getClassLoader().getResource("json/company.json");
        assert url != null;
        String path = url.getPath();
        File jsonFile = new File(path);
        try {
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();

            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 解析json文件，获取快递公司名称对应的信息
     */
    private static String getCompanyInfo(String type){
        //名称必填
        if (StringUtils.isBlank(type)){
            return null;
        }
        String jsonAllInfo = readJsonData();
        //文件读取失败
        if (StringUtils.isBlank(jsonAllInfo)){
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonAllInfo);
        //如果厂商存在
        if (null!=jsonObject && StringUtils.isNotBlank(jsonObject.getString("company"))){
            String companies = jsonObject.getString("company");
            JSONArray jsonArray = JSONArray.parseArray(companies);
            if (null != jsonArray && !jsonArray.isEmpty()){
                for (int i = 0; i< jsonArray.size() ; i++){
                    JSONObject tempCompany = (JSONObject) jsonArray.get(i);
                    if (type.equals(tempCompany.getString("name"))){
                        return tempCompany.getString("number");
                    }
                }
            }
        }
        return null;
    }

    private String getCookies(){
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object> str = restTemplate.getForEntity(EXPRESS_URL,null);
        return null;
    }
}
